package com.example.mardan.views;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.mardan.entity.Couplet;
import com.example.mardan.viewmodel.CoupletViewModel;
import com.example.read.R;

public class CoupletActivity extends AppCompatActivity {
    private TextView coupletTextView;
    private CoupletViewModel coupletViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_couplet);
        coupletTextView = findViewById(R.id.couplet_text_view);

        // 获取根布局视图
        View rootLayout = findViewById(R.id.root_layout);

        coupletViewModel = new ViewModelProvider(this).get(CoupletViewModel.class);
        coupletViewModel.getCouplet("5a5b62b80d4bd6ffa7e3297f647aa513").observe(this, new Observer<Couplet>() {
            @Override
            public void onChanged(Couplet couplet) {
                if (couplet!= null && couplet.getError_code() == 0) {
                    coupletTextView.setText(couplet.getResult().getContent());
                } else {
                    coupletTextView.setText("Error or no data");
                }
            }
        });

        // 为根布局设置点击监听器
        rootLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 再次调用获取对联数据的方法
                coupletViewModel.getCouplet("5a5b62b80d4bd6ffa7e3297f647aa513").observe(CoupletActivity.this, new Observer<Couplet>() {
                    @Override
                    public void onChanged(Couplet couplet) {
                        if (couplet!= null && couplet.getError_code() == 0) {
                            coupletTextView.setText(couplet.getResult().getContent());
                        } else {
                            coupletTextView.setText("Error or no data");
                        }
                    }
                });
            }
        });
    }
}